﻿using System;
using System.IO;
using System.Net;
using System.Web;

namespace Klinkby
{
    static class Ex
    {
        public static bool IsText(this HttpResponse response)
        {
            return response.ContentType.StartsWith("text");
        }


        public static string GetContentString(this HttpWebResponse response)
        {
            string text;
            using (var stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                text = sr.ReadToEnd();
                sr.Close();
            }
            return text;
        }

        public static byte[] ToByteArray(this Stream stream)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                const int bufsize = 1024;
                byte[] buf = new byte[bufsize];
                int len = bufsize;
                while ((len = stream.Read(buf, 0, bufsize)) > 0)
                {
                    ms.Write(buf, 0, len);
                }
                return ms.ToArray();
            }
        }

        public static bool ContainsIgnoreCase(this string dut, string value)
        {
            return dut.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
        }

        public static string ReplaceLastIgnoreCase(this string dut, string oldValue, string newValue)
        {
            int index;
            return ((index = dut.LastIndexOf(oldValue, StringComparison.OrdinalIgnoreCase)) >= 0)
                ? dut.Substring(0, index) + newValue + dut.Substring(index + oldValue.Length)
                : dut;
        }
    }
}